package main

import (
	"gee"
	"html/template"
	"log"
	"net/http"
	"time"
)

func main() {
	r := gee.Default()

	r.GET("/", func(ctx *gee.Context) {
		ctx.String(http.StatusOK, "<h1>hello gee</h1>")
	})

	r.GET("/hello", func(ctx *gee.Context) {
		// expect /hello?name=geektutu
		ctx.String(http.StatusOK, "hello %s, you're at %s", ctx.Query("name"), ctx.Path)
	})

	// curl http://127.0.0.1:9999/login -X POST -d 'username=xxx&password=pwd'
	r.POST("/login", func(ctx *gee.Context) {
		ctx.JSON(http.StatusOK, gee.H{
			"username": ctx.PostForm("username"),
			"password": ctx.PostForm("password"),
		})
	})

	r.GET("/hello/:name", func(ctx *gee.Context) {
		// expect /hello/geektutu
		ctx.String(http.StatusOK, "hello %s, you are at %s\n", ctx.Param("name"), ctx.Path)
	})

	/*r.GET("/assets/*filepath", func(ctx *gee.Context) {
		// expect /assets/css/index.css
		ctx.JSON(http.StatusOK, gee.H{
			"filepath": ctx.Param("filepath"),
		})
	})*/

	v1 := r.Group("/v1")
	{
		v1.GET("/hello", func(ctx *gee.Context) {
			ctx.String(http.StatusOK, "hello v1: %q\n", ctx.Path)
		})
	}
	v2 := r.Group("/v2")
	v2.Use(logRequestTime())
	{
		v2.GET("/hello", func(ctx *gee.Context) {
			ctx.String(http.StatusOK, "hello v2: %q\n", ctx.Path)
		})
	}

	r.Static("/assets", "./static")

	// 注意顺序, 注册函数
	r.SetFuncMap(template.FuncMap{
		"FormatAsDate": func(t time.Time) string {
			return t.Format("2006-01-02 15:04:05")
		},
	})
	// 解析文件夹
	r.LoadHTMLGlob("templates/*")
	r.GET("/date", func(ctx *gee.Context) {
		ctx.HTML(http.StatusOK, "date.tmpl", gee.H{
			"title": "gee",
			"now":   time.Now(),
		})
	})
	
	r.GET("/panic", func(ctx *gee.Context) {
		name := []string{"geek"}
		ctx.String(http.StatusOK, name[100])
	})

	if err := r.Run(":9999"); err != nil {
		panic(err)
	}
}

func logRequestTime() func(ctx *gee.Context) {
	return func(ctx *gee.Context) {
		start := time.Now()
		ctx.Next()
		spend := time.Now().Sub(start).String()
		log.Printf("v2 request:%s  time:%s\n", ctx.Path, spend)
	}
}
